{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import mindspore\n",
    "import mindspore.dataset as ds\n",
    "import mindspore.ops as ops\n",
    "from mindspore import Tensor\n",
    "from d2l import mindspore as d2l\n",
    "\n",
    "true_w = np.array([2, -3.4])\n",
    "true_b = 4.2\n",
    "features, labels = d2l.synthetic_data(true_w, true_b, 1000)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "class SyntheticData():\n",
    "    def __init__(self):\n",
    "        self.features, self.labels = d2l.synthetic_data(true_w, true_b, 1000)\n",
    "\n",
    "    def __getitem__(self, index):\n",
    "        return self.features[index], self.labels[index]\n",
    "    \n",
    "    def __len__(self):\n",
    "        return len(self.labels)\n",
    "\n",
    "def load_array(data_arrays, column_names, batch_size, is_train=True):  \n",
    "    \"\"\"构造一个MindSpore数据迭代器。\"\"\"\n",
    "    dataset = ds.GeneratorDataset(data_arrays, column_names, shuffle=is_train)\n",
    "    dataset = dataset.batch(batch_size)\n",
    "    return dataset\n",
    "\n",
    "batch_size = 10\n",
    "data_iter = SyntheticData()\n",
    "dataset = load_array(data_iter, ['features', 'labels'], batch_size)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[Tensor(shape=[10, 2], dtype=Float32, value=\n",
       " [[ 1.73414111e-01, -1.24616718e+00],\n",
       "  [ 1.02213132e+00, -6.50639892e-01],\n",
       "  [ 1.30825520e+00, -1.22844315e+00],\n",
       "  ...\n",
       "  [-1.60054636e+00,  1.20353259e-01],\n",
       "  [ 7.61325806e-02,  7.83914328e-01],\n",
       "  [ 1.73925209e+00, -3.65485922e-02]]),\n",
       " Tensor(shape=[10, 1], dtype=Float32, value=\n",
       " [[ 8.76539135e+00],\n",
       "  [ 8.46442604e+00],\n",
       "  [ 1.09844027e+01],\n",
       "  ...\n",
       "  [ 6.07668221e-01],\n",
       "  [ 1.68395686e+00],\n",
       "  [ 7.80520296e+00]])]"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "next(iter(dataset))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# nn是神经网络的缩写\n",
    "from mindspore import nn\n",
    "from mindspore.common.initializer import initializer, Normal\n",
    "\n",
    "net = nn.SequentialCell([nn.Dense(2, 1)])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "net[0].weight = initializer(Normal(), net[0].weight.shape, mindspore.float32)\n",
    "net[0].bias = initializer('zero', net[0].bias.shape, mindspore.float32)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "loss = nn.MSELoss()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "optimizer = nn.SGD(net.trainable_params(), learning_rate=0.03)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, loss 0.000214\n",
      "epoch 2, loss 0.000108\n",
      "epoch 3, loss 0.000108\n"
     ]
    }
   ],
   "source": [
    "# 构造前向网络\n",
    "def forward_fn(x, y):\n",
    "    y_hat = net(x)\n",
    "    l = loss(y_hat, y)\n",
    "    return l\n",
    "num_epochs = 3\n",
    "for epoch in range(num_epochs):\n",
    "    for X, y in dataset:\n",
    "        grad_fn = mindspore.value_and_grad(forward_fn, grad_position=None, weights=optimizer.parameters)\n",
    "        l, grads = grad_fn(X, y)\n",
    "        optimizer(grads)\n",
    "    l = forward_fn(mindspore.Tensor(data_iter.features), mindspore.Tensor(data_iter.labels))\n",
    "    print(f'epoch {epoch + 1}, loss {l.asnumpy():f}')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "w的估计误差： [Tensor(shape=[], dtype=Float32, value= -0.00017786)\n",
      " Tensor(shape=[], dtype=Float32, value= -0.000656366)]\n",
      "b的估计误差： [-0.00027466]\n"
     ]
    }
   ],
   "source": [
    "w = net[0].weight.data\n",
    "print('w的估计误差：', true_w - w.reshape(true_w.shape))\n",
    "b = net[0].bias.data\n",
    "print('b的估计误差：', true_b - b)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python [conda env:mindspore2.0]",
   "language": "python",
   "name": "conda-env-mindspore2.0-py"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.15"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
